<template>
  <div class="Cart-box">
    <!-- 搜索框 -->
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="GoBack"
    >
      <template #right>
        <van-icon name="ellipsis" size="18" />
      </template>
    </van-nav-bar>
    <!-- 购物车列表 -->
    <div class="Cart-content">
      <!-- 购物车为空 -->
      <van-empty
        description="描述文字"
        v-if="goodslist.length ? false : true"
      />
      <!-- 购物车商品列表 -->
      <van-list
        class="details-box"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        offset="0"
        @load="onLoad"
        v-show="Boolean"
      >
        <van-swipe-cell
          v-for="(item, index) in goodslist"
          :key="item.proid"
          class="cart-list"
        >
          <van-card
            :price="item.originprice"
            :desc="item.proname"
            class="goods-card"
            :thumb="item.img1"
          >
            <template #num>
              <van-stepper
                v-model="item.num"
                theme="round"
                button-size="22"
                disable-input
                @plus="addEvent(index, item.cartid)"
                @minus="minEvent(index, item.cartid)"
              />
            </template>
          </van-card>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="deleteGoods(item.cartid)"
            />
          </template>
          <!-- 单选框 -->
          <van-checkbox
            v-model="item.flag"
            class="cart-radio"
            @click="getCheck(index, item.cartid)"
          ></van-checkbox>
        </van-swipe-cell>
      </van-list>
      <!-- 文字分条 -->
      <van-divider
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
      >
        可能你想要
      </van-divider>
      <!-- 猜你喜欢 -->
      <div class="details-list">
        <van-list
          class="details-box1"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          offset="0"
          @load="onLoad"
        >
          <div
            v-for="item in goodslist1"
            :key="item.proid"
            @click="goGoodsDetail(item.proid)"
          >
            <img :src="item.img1" />
            <p class="introduce1">{{ item.proname }}</p>
            <p class="price1">¥{{ item.originprice }}</p>
          </div>
        </van-list>
      </div>
    </div>
    <!-- 提交订单 -->
    <van-submit-bar
      :price="money()"
      button-text="提交订单"
      @submit="onSubmit"
      v-if="goodslist.length ? true : false"
    >
      <van-checkbox v-model="checked" @click="getAllSelect">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import FooterBarVue from "@/components/FooterBar.vue";
export default {
  name: "Cart",
  data() {
    return {
      goodslist: [],
      goodslist1: [],
      // 列表
      list: [],
      loading: false,
      finished: false,
      //
      Boolean: true,
      //单选
      value: "",
      //全选
      checked: false,
      // money: ''
    };
  },
  components: {
    FooterBarVue,
  },
  created() {
    let token = localStorage.getItem("token");
    let userid = localStorage.getItem("userid");
    if (!token) {
      this.Boolean = !this.Boolean;
    }
    this.service({
      method: "post",
      url: "/cart/list",
      headers: { token },
      data: `userid=${userid}`,
    }).then((res) => {
      if (res.data.code == 200) {
        this.goodslist = [...this.goodslist, ...res.data.data];
      } else {
        if (token) {
          this.$toast.fail("您的购物车为空！");
        } else {
          this.$toast.fail("获取购物车失败！");
        }
      }
    });
    /* 猜你喜欢列表页 */
    this.service({
      url: "/pro/recommendlist",
      params: {
        count: this.pageIndex,
        limitNum: 10,
      },
    })
      .then((res) => {
        if (res.data.code == 200) {
          // console.log("res.data.data.length",res.data.data.length);
          // console.log(res);
          this.goodslist1 = [...this.goodslist1, ...res.data.data];
          this.loading = false;
          this.pageIndex++;
        }
      })
      .catch((err) => {
        console.log("err", err);
      });
  },
  methods: {
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1);
        }

        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if (this.list.length >= 40) {
          this.finished = true;
        }
      }, 1000);
    },
    /* 点击返回 */
    GoBack() {
      this.$router.go(-1);
      this.service({
        url: "/pro/recommendlist",
        params: {
          count: this.pageIndex,
          limitNum: 10,
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            // console.log("res.data.data.length",res.data.data.length);
            // console.log(res);
            this.goodslist = [...this.goodslist, ...res.data.data];
            this.loading = false;
            this.pageIndex++;
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 点击搜索
    onSubmit() {
      this.$router.push("/payMent");
    },
    // 点击加
    addEvent(index, cartid) {
      let token = localStorage.getItem("token");
      let num = ++this.goodslist[index].num;

      this.service({
        method: "post",
        url: "/cart/updatenum",
        headers: { token },
        data: `cartid=${cartid}&num=${num}`,
      }).then((res) => {
        // console.log(res);
      });
    },
    // 点击减
    minEvent(index, cartid) {
      let token = localStorage.getItem("token");
      let num = --this.goodslist[index].num;

      this.service({
        method: "post",
        url: "/cart/updatenum",
        headers: { token },
        data: `cartid=${cartid}&num=${num}`,
      }).then((res) => {
        // console.log(res);
      });
    },
    // 点击删除
    deleteGoods(cartid) {
      let token = localStorage.getItem("token");
      this.service({
        method: "post",
        url: "/cart/remove",
        headers: { token },
        data: `cartid=${cartid}`,
      }).then((res) => {
        if (res.data.code == 200) {
          this.$toast.success("删除成功！");
          this.goodslist = this.goodslist.filter(
            (item) => item.cartid != cartid
          );
        } else {
          this.$toast.fail("删除失败！");
        }
      });
    },
    //点击单选框
    getCheck(index, cartid) {
      let token = localStorage.getItem("token");
      let flag = this.goodslist[index].flag;
      this.service({
        method: "post",
        headers: { token },
        url: "/cart/selectone",
        data: `cartid=${cartid}&flag=${flag}`,
      }).then((res) => {
        if (res.data.code == 200) {
          console.log(res);
        }
      });
    },
    // 点击提交
    onSubmit() {
      
      let userid = localStorage.getItem("userid");
      let token = localStorage.getItem("token");
      this.service({
        method: "post",
        url: "/order/addOrder",
        headers: { token },
        data: `userid=${userid}`,
      })
      .then((res)=>{
        if(res.data.code==200) {
          this.$toast.success ("添加订单成功！")
        }else {
          this.$toast.fail ("添加订单失败！")
        }
      })
      setTimeout(()=>{
        this.$router.push("/payMent");
      },1000)
    },
    // 点击商品
    goGoodsDetail(id) {
      this.$router.push("/GoodsDetail/" + id);
    },
    /* 点击全选 */
    getAllSelect() {
      console.log("this.checked", this.checked);
    },
    /* 购物车总钱数 */
    money(){
      let priceList = this.goodslist.filter(item=>{
        return item.flag
      })
      return priceList.reduce((sum,item)=>{
        return sum += item.num * item.originprice * 100
      },0)
    }
  },
};
</script>

<style scoped>
.Cart-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.Cart-content {
  flex: 1;
  overflow: auto;
}
.cart-list {
  padding-left: 1.25rem;
  position: relative;
}
.cart-radio {
  position: absolute;
  top: 2.625rem;
  left: -0.9375rem;
  /* border: 1px solid black; */
}
.goods-box {
  display: flex;
  width: 100%;
  height: 5.5rem;
  justify-content: space-between;
  margin: 0.625rem 0 0.625rem 0;
}
.goods-image {
  width: 35%;
  height: 100%;
}
.goods-image img {
  width: 100%;
  height: 100%;
}
.goods-introduce {
  width: 70%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.introduce {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  widows: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.price {
  display: flex;
  justify-content: space-around;
}
/* 商品列表页 */
.details-box1 {
  width: 100%;
  font-size: 14px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  /* column-count: 2;
  column-gap: 5px; */
}
.details-box1 div {
  width: 49%;
  text-align: center;
}
.details-box1 div img {
  width: 100%;
}
.introduce1 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  widows: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.price1 {
  text-align: left;
  color: brown;
  font-size: 18px;
}
/* 删除 */
.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}
</style>